<template>
  <el-form
    ref="loginForm"
    :model="loginForm"
    :rules="loginRules"
    label-position="left"
    label-width="0px"
    class="login-form"
  >
    <div class="login-form-title">请输入验证码登录</div>
    <el-form-item
      prop="phone"
      style="width:100%;"
    >
      <el-input
        v-model="loginForm.phone"
        class="login-form-account"
        placeholder="请输入账户"
      />
    </el-form-item>
    <el-form-item prop="code">
      <el-input
        v-model="loginForm.code"
        class="login-form-password"
        placeholder="请输入验证码"
      >
        <el-button
          slot="append"
          :disabled="disableCodeBtn"
          type="text"
          style="width:100px;"
          @click="getCode"
        >{{ codeMes }}</el-button>
      </el-input>
    </el-form-item>
    <el-button
      :loading="loading"
      class="login-form-submit"
      size="medium"
      style="width:100%;"
      @click.native.prevent="handleLogin"
    >{{ !loading ? '登录' : '登 录 中...' }}</el-button>
  </el-form>

</template>

<script>
import { hex_md5 } from '@/utils/md5'
import { setToken } from '@/utils/auth'
import { getPhoneCode, phoneLogin } from '@/api/loginDefine'
import Config from '@/config'
import Cookies from 'js-cookie'
export default {
  name: 'PhoneLogin',
  props: {
    from: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      codeUrl: '',
      cookiePass: '',
      loginForm: {
        phone: '',
        code: '',
        rememberMe: false
      },
      loginRules: {
        phone: [{ required: true, trigger: 'blur', message: '手机号不能为空' }],
        code: [{ required: true, trigger: 'blur', message: '验证码不能为空' }]
      },
      loading: false,
      redirect: undefined,
      codeMes: '获取验证码',
      disableCodeBtn: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCookie()
  },
  methods: {
    getCode() {
      console.log('点击')
      this.disableCodeBtn = true
      const [phone, type, isInDb, timestamp] = [
        this.loginForm.phone,
        1,
        1,
        Math.round(new Date())
      ]
      // console.log([phone, type, isInDb, timestamp])
      const reqParam = {
        phone: phone,
        signcode: hex_md5(phone + type + isInDb + timestamp),
        type: type,
        isindb: isInDb,
        timestamp: timestamp
      }
      const that = this
      let wait = 60

      // 倒计时
      function countDown() {
        if (wait === 0) {
          that.codeMes = '获取验证码'
          that.disableCodeBtn = false
        } else {
          wait--
          that.codeMes = wait + 'S'
          setTimeout(function() {
            countDown()
          }, 1000)
        }
      }

      getPhoneCode(reqParam).then(res => {
        console.log(res)
        if (res.code === '100000000000') {
          countDown()
        } else {
          this.$notify({
            title: res.msg,
            type: 'warning',
            duration: 1500
          })
          that.codeMes = '获取验证码'
          that.disableCodeBtn = false
        }
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      // 保存cookie里面的加密后的密码
      this.cookiePass = password === undefined ? '' : password
      password = password === undefined ? this.loginForm.password : password
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: ''
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const [phone, code, timestamp] = [
            this.loginForm.phone,
            this.loginForm.code,
            Math.round(new Date())
          ]
          console.log([phone, code, timestamp])
          const reqParam = {
            phone: phone,
            timestamp: timestamp,
            code: code,
            signcode: hex_md5(phone + code + timestamp)
          }
          phoneLogin(reqParam)
            .then(res => {
              console.log(res)
              this.loading = false
              let [type, message] = ['success', '']
              if (res.code === '100000000000') {
                type = 'success'
                message = '登陆成功！'
                setToken(res.data.token)
                Cookies.set('company_id', res.data.companycode, {
                  expires: Config.passCookieExpires
                })
                this.$store.dispatch('setLoadMenus', true)
                this.$router.push({ path: this.redirect || '/' })
              } else {
                type = 'error'
                message = res.msg
              }
              this.$notify({
                title: message,
                type: type,
                duration: 1500
              })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scope>
.login-form {
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.el-input-group__append {
  cursor: pointer;
  background: #3a4450 !important;
  color: #fff;
}
</style>
